package com.jarvis.du.httplib.cookie;


import com.jarvis.du.httplib.cookie.store.CookieStore;
import com.jarvis.du.httplib.cookie.store.MemoryCookieStore;

import java.util.concurrent.TimeUnit;

import okhttp3.CookieJar;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Author: dyj
 * Date: 2018/11/20 19:51
 * E-mail: duyangjun1991@163.com
 */

public class RetrofitManager {
    Retrofit retrofit;
    private OkHttpClient mOkHttpClient;

    public RetrofitManager() {
        init();
    }

    void init() {
        HttpLoggingInterceptor logging = new HttpLoggingInterceptor();
        logging.setLevel(HttpLoggingInterceptor.Level.BODY);
//        }else {
//            logging.setLevel(HttpLoggingInterceptor.Level.NONE);
//        }
        mOkHttpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .readTimeout(20, TimeUnit.SECONDS)
//                .socketFactory()
//                .hostnameVerifier()
                .addNetworkInterceptor(logging)
                .cookieJar(new CookieJarImpl(new MemoryCookieStore()))
                .build();
        retrofit = new Retrofit.Builder()
                .baseUrl("https://api.github.com")
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(mOkHttpClient)
                .build();
    }

    /**
     * @param service
     * @param <T>
     * @return
     */
    public <T> T createApi(Class<T> service) {
        return retrofit.create(service);
    }

    public CookieStore getCookieStore() {
        CookieJar cookieJar = mOkHttpClient.cookieJar();
        if (cookieJar instanceof CookieJarImpl) {
            CookieJarImpl cookieStore = (CookieJarImpl) cookieJar;
            return cookieStore.getCookieStore();
        } else {
            return null;
        }
    }

    /**
     *
     */
    public void cleanCookie() {
        if (getCookieStore() != null) {
            getCookieStore().removeAll();
        }
    }
}
